<!--添加修改角色信息-->
<template>
  <a-modal v-model="showAddTable" :mask-closable="false" :closable="false" :width="1200"
           :title="title ? '课程新增' : '课程编辑'"
           :maskClosable="false"
           :destroyOnClose="true">
    <a-form :form="form" class="modelSearch">
      <a-row>
        <a-col span="12">
          <a-form-item label="课程名称：" prop="name" v-bind="formStyle">
            <a-input
                placeholder="请输入课程名称" ref="re"
                v-decorator="[
                        'name',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="实验室：" prop="classroomId" v-bind="formStyle">
            <a-select
                v-decorator="['classroomId', { rules: [{ required: true, message: '选择实验室' }] }]"
                placeholder="请选择实验室" v-model="classroomId"
                @select="changeLabList"
            >
              <a-select-option v-for="item in labSelectList" :value="item.value"
                               :key="item.value">{{item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="授课老师：" prop="teacherId" v-bind="formStyle">
            <a-select
                v-decorator="['teacherId', { rules: [{ required: true, message: '选择授课老师' }] }]"
                placeholder="请选择授课老师" v-model="teacherId"
            >
              <a-select-option v-for="item in teacherSelectList" :value="item.value"
                               :key="item.value">{{item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="实验阶段数：" prop="stageCount" v-bind="formStyle">
            <a-input
                placeholder="请输入实验阶段数" ref="re"
                v-decorator="[
                        'stageCount',
                        {
                            rules: [
                                { required: true, message: '请输入正整数' },
                                { validator: this.verify.validateInteger.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="实验时长（小时）：" prop="duration" v-bind="formStyle">
            <a-input-number style="width: 390px"
                            placeholder="请输入实验时长" ref="duration"
                            v-decorator="[
                        'duration',
                        {
                            rules: [
                                { required: true, message: '请输入正整数' },
                            ]
                        }
                    ]"
                            :min="0" :max="4" :precision="0"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="课表背景色：" prop="backgroundColor" v-bind="formStyle">
            <el-color-picker style="height: 30px;width: 30px" v-model="backgroundColor" @change="changeBackgroundColor"></el-color-picker>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="实验简介：" prop="description" v-bind="formStyle">
            <a-textarea placeholder="请输入实验简介"  ref="description" v-decorator="['description',{   rules: [],
                               getValueFromEvent: (event) => {
                                   return this.verify.formalhundredWithOutSpace(event)
                               }
                            }]" :rows="3" />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="成绩计算方式：" prop="scoreCalcWay" v-bind="formStyle" required>
            <a-radio-group  v-decorator="['scoreCalcWay', { initialValue: '1' }]"  v-model="scoreCalcWay"  @change="onScoreCalcWayChange">
              <a-radio value="1">手动输入</a-radio>
              <a-radio value="2">自动计算</a-radio>
            </a-radio-group>
            <a-button type="primary" size="default" @click="addCourseRule()">新增规则</a-button>
          </a-form-item>
        </a-col>
      </a-row>

      <a-table v-if="scoreCalcWay === '2'"
          :columns="columns" :dataSource="courseRuleList" :rowKey="record => record.index" style="height: 300px;overflow-y: auto"
               :pagination="false">
        <span slot="scoreScaleMin" slot-scope="text, record, index">
          <a-input-number :disabled="true" v-model="record.scoreScaleMin" :key="'scoreScaleMin'+index+record.rowIndex"
                          placeholder=""   :min="1" :max="500" :precision="0" />
        </span>
        <span slot="scoreScaleMax" slot-scope="text, record, index">
          <a-input-number  v-model="record.scoreScaleMax" :key="'scoreScaleMax'+index+record.rowIndex"
              placeholder="名次" @change="changeInput($event,index)"  :min="0" :max="500" :precision="0" />
        </span>
        <span slot="score" slot-scope="text, record, index">
          <a-input-number v-model="record.score" :key="'score'+index+record.rowIndex"
                          placeholder="得分" @change="changeScoreInput($event,index)"  :min="1" :max="100" :precision="0" />
        </span>
        <span slot="scoreLevel" slot-scope="text, record, index">
          <a-input :key="'level'+index+record.rowIndex"
              placeholder="请输入成绩水平" ref="re" v-model="record.scoreLevel"
                   @change="changeScoreInput($event,'scoreLevel',index)"
          />
        </span>
        <span slot="operation" slot-scope="text, record, index" class="table-operation">
                        <a @click="removeCourseRule(index)">
                                          删除</a>
                </span>
      </a-table>
    </a-form>
    <div slot="footer">
      <a-button type="default" size="default" @click="cancelApply()">取消</a-button>
      <a-button type="primary" size="default" @click="saveApply()">确定</a-button>
    </div>
  </a-modal>
</template>

<script>
import verify from 'libs/verify'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import elColorPicker from 'el-color-picker'

export default {
  name: 'addEdit',
  components: {
    AFormItem,
    elColorPicker,
  },
  data() {
    return {
      verify,
      form: this.$form.createForm(this),
      showAddTable: false,
      input: false,
      scoreCalcWay: '1',
      name: '',
      classroomId: '',
      teacherId: '',
      duration: 2,
      allowStuCount: 0,
      stageCount: 1,
      weekStudyHour: 1,
      backgroundColor: '',
      rowIndex: 10,
      courseRuleList:[],
      courseRuleObj:{
        rowIndex:0,
        courseId:'',
        scoreScaleMin:'',
        scoreScaleMax:'',
        score:'',
        scoreLevel:'',
      },
      columns: [
        {title: '提交排名上限', dataIndex: 'scoreScaleMin', key: 'scoreScaleMin',width: '20%',  scopedSlots: {customRender: 'scoreScaleMin'}},
        {title: '提交名次', dataIndex: 'scoreScaleMax', key: 'scoreScaleMax', width: '20%', scopedSlots: {customRender: 'scoreScaleMax'}},
        {title: '得分', dataIndex: 'score', key: 'score', width: '20%', scopedSlots: {customRender: 'score'}},
        {title: '成绩', dataIndex: 'scoreLevel', key: 'scoreLevel', width: '30%', scopedSlots: {customRender: 'scoreLevel'}},
        {title: '操作', key: 'operation', width: '10%', scopedSlots: {customRender: 'operation'}}
      ],
    }
  },
  computed: {
    labSelectList() {
      return this.$store.state.acManage.labSelectList
    },
    teacherSelectList() {
      return this.$store.state.courseManage.teacherSelectList
    },
    formStyle() {
      return this.$store.state.common.formStyle
    }
  },
  props: {

    title: {
      type: Boolean,
      required: true
    },
    objDTO: {
      type: Object,
      required: true
    }
  },
  watch: {},
  methods: {
    onScoreCalcWayChange(e){
      this.scoreCalcWay = e.target.value
    },
    changeBackgroundColor(value){
      this.backgroundColor = value
    },
    changeLabList ( value ) {
      let _this = this;
      let labSelectList = _this.labSelectList;
      for (let index in labSelectList){
        if (labSelectList[index].value === value){
          let labObj = labSelectList[index].record
          _this.allowStuCount = labObj.diskNum *2
        }
      }
    },

    addCourseRule(){
      this.courseRuleObj = {
        rowIndex:this.rowIndex,
        courseId:'',
        scoreScaleMin:'',
        scoreScaleMax:'',
        scoreLevel:'',
        score:'',
      }
      this.rowIndex = this.rowIndex+1
      this.courseRuleList.push(this.courseRuleObj)
      this.courseRuleList[0].scoreScaleMin=1
      if (this.courseRuleList.length >1){
        this.courseRuleList[this.courseRuleList.length-1].scoreScaleMin=this.courseRuleList[this.courseRuleList.length-2].scoreScaleMax+1
      }
    },

    removeCourseRule(index){
      this.courseRuleList.splice(index,1)
      this.courseRuleList[0].scoreScaleMin=1
    },
    changeInput(value,index){
      let maxProp = 'scoreScaleMax'
      let minProp = 'scoreScaleMin'
      this.courseRuleList[index][maxProp] = value
      if (index < this.courseRuleList.length -1){
        this.courseRuleList[index+1][minProp] = value+1
      }
      },
    changeScoreInput(value,index){
      this.courseRuleList[index]['score'] = value
      },
    /**
     * Function    : saveApply
     * Description : 打开弹框
     * Input       : none
     * Return      : none
     */
    showModal() {
      this.showAddTable = true
      this.rowIndex = 0
      this.courseRuleList=[]
      this.courseRuleObj={
        rowIndex:0,
        courseId:'',
        scoreScaleMin:'',
        scoreScaleMax:'',
        scoreLevel:'',
      }
    },
    /**
     * Function    : showEdit
     * Description : 编辑时显示
     * Input       : opt单个所有数据
     * Return      : none
     */
    showEdit(opt) {
      this.showAddTable = true
      this.id = opt.id
      this.rowIndex = 10
      this.courseRuleList=[]
      this.courseRuleObj={
        rowIndex:0,
        courseId:'',
        scoreScaleMin:'',
        scoreScaleMax:'',
        scoreLevel:'',
      }
      let _this = this;
      _this.$store.dispatch('getCourseInfoAct', {id: opt.id}).then(response => {
        let courseInfo = {}
        if (response.code === 0) {
          courseInfo = response.data
          _this.$nextTick(() => {
            _this.form.setFieldsValue(_this.$pick(courseInfo, [
              'name', 'scoreCalcWay', 'classroomId', 'teacherId','duration',
              'allowStuCount', 'stageCount', 'weekStudyHour', 'backgroundColor','description'
            ]))
            _this.backgroundColor = courseInfo.backgroundColor
            _this.allowStuCount = courseInfo.allowStuCount
            _this.scoreCalcWay = courseInfo.scoreCalcWay
            _this.courseRuleList = courseInfo.courseRuleList
          })
        } else {
          _this.$message.error(response.message)
        }
      })

    },

    /**
     * Function    : saveApply
     * Description : 角色信息新增、编辑保存
     * Input       : name
     * Return      : none
     */
    saveApply() {
      let _this = this
      if (_this.courseRuleList.length === 0 && _this.scoreCalcWay === '2'){
        this.$message.error('成绩规则不可为空')
        return
      }
      let courseRuleList =  _this.courseRuleList
      for (let index in courseRuleList){
        if (!courseRuleList[index] .scoreScaleMin || !courseRuleList[index].scoreScaleMax || !courseRuleList[index].score){
          this.$message.error('成绩规则内容不可包含空值')
          return
        }
        if (index > 0 && (courseRuleList[index] .scoreScaleMin < courseRuleList[index-1] .scoreScaleMin )){
          this.$message.error('成绩规则排名区间有重复')
          return;
        }
      }
      this.form.validateFields((err, value) => {
        if (!err) {
          let para = {}
          para.name = value.name
          para.teacherId = value.teacherId
          para.classroomId = value.classroomId
          para.duration = value.duration
          para.allowStuCount = this.allowStuCount
          para.stageCount = value.stageCount
          para.weekStudyHour = value.weekStudyHour
          para.description = value.description
          para.scoreCalcWay = this.scoreCalcWay
          para.backgroundColor = this.backgroundColor
          para.courseRuleList = this.courseRuleList
          if (!this.title) {
            para.id = this.id
          }
          this.$store.dispatch('saveCourseAct', para).then(response => {
            this.showAddTable = false
            if (response.code === 0) {
              this.$emit('init')
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },

    /**
     * Function    : cancelApply
     * Description : 取消弹出框
     * Input       : val
     * Return      : none
     */
    cancelApply() {
      this.showAddTable = false
      let _this = this
      this.backgroundColor = ''
      this.scoreCalcWay = '1'
      setTimeout(function () {
        _this.form.resetFields()
      }, 100)
    },
    initData() {
      this.$store.dispatch('getLabListAct', {})
      this.$store.dispatch('getTeacherSelectListAct', {})
    }

  },

  created() {
    this.initData()
  }
}
</script>

<style>
.ant-table-thead {
  position: sticky;
  top: 0px;
  z-index: 1;
}
</style>
